package com.tj.template.application.payment;

import com.fqgj.common.utils.CollectionUtils;
import com.tj.bo.account.client.WithdrawService;
import com.tj.bo.account.client.vo.WithDrawPayoutNotifyVO;
import com.tj.bo.payment.client.PayCommandService;
import com.tj.bo.payment.client.PayQueryService;
import com.tj.bo.payment.client.enums.PayOrderStatusEnum;
import com.tj.bo.payment.client.enums.PayOrderTypeEnum;
import com.tj.bo.payment.client.vo.BusinessVO;
import com.tj.bo.payment.client.vo.DfPaymentOrderResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * 代付订单
 *
 * @author ZhangChao
 * @since 2021/7/19
 */
@Service
public class DfPayOrderService {
    private final Logger logger = Logger.getLogger(DfPayOrderService.class.getName());
    @Autowired
    private PayQueryService payQueryService;
    @Autowired
    private PayCommandService payCommandService;
    @Autowired
    private WithdrawService withdrawService;

    @Scheduled(fixedDelay = 300000)
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void syncDfPayOrder(){
        logger.info("代付订单同步开始");
        List<String> dfOrderCodes = payQueryService.queryPaymentOrderCodes(PayOrderStatusEnum.NOT_PAY, PayOrderTypeEnum.DF_PAYMENT);
        if (CollectionUtils.isNotEmpty(dfOrderCodes)){
            for(String orderCode : dfOrderCodes){
                try{
                    DfPaymentOrderResultVO dfPaymentOrderResultVO = payCommandService.syncDfPayOrder(orderCode);
                    if (dfPaymentOrderResultVO.getStatus().equals(PayOrderStatusEnum.NOT_PAY)){
                        continue;
                    }
                    WithDrawPayoutNotifyVO withDrawPayoutNotifyVO = new WithDrawPayoutNotifyVO();
                    BusinessVO businessVO = dfPaymentOrderResultVO.getBusinessVO();
                    withDrawPayoutNotifyVO.setWithdrawOrderNo(businessVO.getAttach());
                    if (dfPaymentOrderResultVO.getStatus().equals(PayOrderStatusEnum.PAID)){
                        withDrawPayoutNotifyVO.setCode("0000");
                    }else{
                        withDrawPayoutNotifyVO.setCode("0001");
                    }
                    withdrawService.withDrawPayoutNotify(withDrawPayoutNotifyVO);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        logger.info("代付订单同步结束");
    }
}
